#include "form_jsdz.h"
#include "ui_form_jsdz.h"
#include "pub_var.h"

#include <QJsonObject>
#include <QJsonDocument>
#include <QJsonArray>
#include <QSettings>
#include <QMessageBox>
#include <QDebug>
#include <QSqlError>
#include <QSqlRecord>
#include <QDateTime>
#include <QFile>
#include <QFileDialog>


Form_jsdz::Form_jsdz(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Form_jsdz)
{
    ui->setupUi(this);

    QSettings setIni("clin.ini", QSettings::IniFormat);
    //恢复当前窗口位置
    QRect rct = setIni.value("windowState/jsdz").toRect();
    this->setGeometry(rct);

    //数据库连接
    qrm = new QSqlQuery(pub::db_m);
    qro = new QSqlQuery(pub::db_o);

    //默认日期
    QDate dt;
    ui->deStart->setDate(dt.currentDate());
    ui->deEnd->setDate(dt.currentDate());

    request.setUrl(QUrl(pub::hos_ybjy));
    //request.setUrl(QUrl("http://192.168.1.233:9999"));
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
//    request.setHeader(QNetworkRequest::ContentTypeHeader, "multipart/form-data");
}

Form_jsdz::~Form_jsdz()
{
    delete ui;
}

void Form_jsdz::closeEvent(QCloseEvent *event)
{
    Q_UNUSED(event);
    QSettings setIni("clin.ini", QSettings::IniFormat);
    setIni.setValue("windowState/jsdz", QVariant(this->geometry()));

}

void Form_jsdz::showEvent(QShowEvent *event)
{
    //QMessageBox::information(this,"note","widnow is show");
}

void Form_jsdz::on_pbRun_clicked()
{
    //对总账
    QJsonObject in;
    if(! putBaseIn(  in, "3201") ){
        return;
    }

    QJsonObject inpu,inpud;

    inpu.insert("insutype", ui->cbbXz->currentText());//险种
    inpu.insert("clr_type", ui->cbbQslb->currentText());//清算类别
    inpu.insert("setl_optins", pub::hos_insuplc);//结算经办机构
    //inpu.insert("setl_optins", pub::hos_ybbh_old);//结算经办机构
    //inpu.insert("setl_optins", pub::hos_ybbh);//结算经办机构
    inpu.insert("stmt_begndate", ui->deStart->date().toString("yyyy-MM-dd")+" 00:00:00");//对账开始日期
    inpu.insert("stmt_enddate", ui->deEnd->date().toString("yyyy-MM-dd")+" 23:59:59");//对账结束日期
    inpu.insert("medfee_sumamt", ui->le1->text());//医疗费总额
    inpu.insert("fund_pay_sumamt",ui->le2->text());//基金支付总额
    inpu.insert("acct_pay",ui->le3->text());//个人账户支付金额
    inpu.insert("fixmedins_setl_cnt",ui->le5->text());//定点医药机构结算笔数

    inpud.insert("data",inpu);
    in.insert("input", inpud);

    QJsonDocument indoc ;
    indoc.setObject(in);
    qDebug()<<"3201 indoc "<<indoc;

    //保存入参日志
    sq = "update com_business set v_in = '"
            + indoc.toJson(QJsonDocument::Compact)
            + "' where jyls = '" + currentMsgid + "'";

    if(!qrm->exec(sq)){
        QMessageBox::information(this,"错误","保存入参日志失败！");
        qDebug()<<sq;
    }

    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
    //request.setHeader(QNetworkRequest::ContentTypeHeader, "multipart/form-data");
    QNetworkReply* reply = manager.post(request,indoc.toJson());

    QEventLoop eventLoop;
    QObject::connect(reply, SIGNAL(finished()), &eventLoop, SLOT(quit()));
    eventLoop.exec(); // 进入等待返回，但ui事件循环依然进行。


    qDebug()<<" request 3201 is returned";

    QVariant statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);

    if(!statusCode.isValid()){
        QMessageBox::warning(NULL,"注意","http 请求状态错误: " + statusCode.toString());
        return ;
    }

    QNetworkReply::NetworkError err = reply->error();

    if(err != QNetworkReply::NoError){
        QMessageBox::warning(NULL,"注意",reply->errorString());
        return ;
    }

    QByteArray bt = reply->readAll();
    QString t = QString::fromLocal8Bit(bt);

    QJsonParseError json_error;
    QJsonDocument jsdc = QJsonDocument::fromJson(t.toUtf8(), &json_error);
    if(json_error.error != 0 ){
        QMessageBox::warning(NULL,"注意","返回信息解析错误 " + json_error.errorString());

        return ;
    }
    qDebug()<< "3201 outDoc "<<jsdc;
    QJsonObject jsob = jsdc.object();

    sq = "update com_business set v_out = '"
            + jsdc.toJson(QJsonDocument::Compact)
            + "' where jyls = '" + currentMsgid + "'";

    if(!qrm->exec(sq)){
        QMessageBox::information(this,"错误","保存出参日志失败！");
        qDebug()<<sq;
    }


    if(jsob.value("infcode").toInt() != 0){
        QString t = jsob.value("err_msg").toString();
        QMessageBox::warning(NULL,"注意","3201 交易失败：" + t );

        return ;
    }
    ret3201 = jsob.value("output").toObject().value("stmtinfo").toObject();

    //qDebug()<<ret3201.value("setl_optins").toString();

    QMessageBox::information(this,"注意","对账返回 " + ret3201.value("stmt_rslt").toString()
                             + " , " + ret3201.value("stmt_rslt_dscr").toString());

}

void Form_jsdz::on_pbUpload_clicked()
{


    //明细对账

    QString fileName = QFileDialog::getOpenFileName(this, "打开准备上传的对账文件",  "d:/0down/",  "(*.zip *.txt)",  0);
    if (fileName.isNull()){
        return;
    }

    QString  pureFileName,fileSuffix;
    QFileInfo fileinfo;
    fileinfo = QFileInfo(fileName);
    pureFileName = fileinfo.fileName();//文件名

    QByteArray bt;

    QFile f(fileName);
    if(!f.open(QIODevice::ReadOnly)){
        QMessageBox::information(this,"note","open file failed.");
        return;
    }
    bt = f.readAll();
    f.close();


    qDebug()<<bt;

    int len = bt.length();

    //base64方式传送
    QString btStr = QString::fromLatin1(bt.toBase64());
    QJsonValue btS0 = btStr;

    //char类型json数组传送
    QJsonArray jsar;
    for(int i = 0; i < len; i++){

        jsar.insert(i, char(bt[i]));

    }



    QJsonObject in;
    QJsonObject inpu,inpud;
    QJsonDocument d;

    if(!putBaseIn(  in, "9101") ){
        return;
    }


    inpu.insert("in",  btS0);//文件数据
    //inpu.insert("in",  jsar);//文件数据

    inpu.insert("filename", pureFileName.left(pureFileName.length()-3) + "txt");//文件名
    inpu.insert("fixmedins_code", pub::hos_ybbh);//定点医药机构

    inpud.insert("fsUploadIn",inpu);
    in.insert("input", inpud);

    QJsonDocument indoc ;
    indoc.setObject(in);

    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");


    QNetworkReply* reply = manager.post(request,indoc.toJson());

    QEventLoop eventLoop;
    QObject::connect(reply, SIGNAL(finished()), &eventLoop, SLOT(quit()));
    eventLoop.exec(); // 进入等待返回。


    qDebug()<<" request 9101 is returned";

    QVariant statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);

    if(!statusCode.isValid()){
        QMessageBox::warning(NULL,"注意","http 请求状态错误: " + statusCode.toString());
        return ;
    }

    QNetworkReply::NetworkError err = reply->error();

    if(err != QNetworkReply::NoError){
        QMessageBox::warning(NULL,"注意",reply->errorString());
        return ;
    }

    QByteArray btret = reply->readAll();
    QString t = QString::fromLocal8Bit(btret);

    QJsonParseError json_error;

    QJsonDocument jsdc = QJsonDocument::fromJson(t.toUtf8(), &json_error);
    if(json_error.error != 0 ){
        QMessageBox::warning(NULL,"注意","返回信息解析错误 " + json_error.errorString());

        return ;
    }
    qDebug()<< "9101 outDoc "<<jsdc;
    QJsonObject jsob = jsdc.object();

    sq = "update com_business set v_out = '"
            + jsdc.toJson(QJsonDocument::Compact)
            + "' where jyls = '" + currentMsgid + "'";

    if(!qrm->exec(sq)){
        QMessageBox::information(this,"错误","保存出参日志失败！");
        qDebug()<<sq;
    }

    if(jsob.value("code").toInt() != 0){
        QString t = jsob.value("err_msg").toString();
        QMessageBox::warning(NULL,"注意","9101 交易失败：" + t );

        return ;
    }
    ret9101 = jsob.value("output").toObject();
    //.value("stmtinfo").toObject()

    qDebug()<<ret9101.value("file_qury_no").toString();


    //9101 结束



    //调用3202


    in = d.object();
    inpu = d.object();
    inpud = d.object();

    if(!putBaseIn(  in, "3202") ){
        return;
    }

    inpu.insert("setl_optins", pub::hos_insuplc);//	结算经办机构
    //inpu.insert("setl_optins", pub::hos_ybbh_old);//	结算经办机构
    //inpu.insert("setl_optins", pub::hos_ybbh);//	结算经办机构
    inpu.insert("file_qury_no", ret9101.value("file_qury_no").toString());//	文件查询号

    inpu.insert("stmt_begndate", ui->deStart->date().toString("yyyy-MM-dd")+" 00:00:00");//对账开始日期
    inpu.insert("stmt_enddate", ui->deEnd->date().toString("yyyy-MM-dd")+" 23:59:59");//对账结束日期

    inpu.insert("medfee_sumamt", ui->le1->text());//医疗费总额
    inpu.insert("fund_pay_sumamt",ui->le2->text());//基金支付总额

    //    inpu.insert("acct_pay",ui->le3->text());//个人账户支付金额
    inpu.insert("cash_payamt", ui->le4->text());//	现金支付金额

    inpu.insert("fixmedins_setl_cnt",ui->le5->text());//定点医药机构结算笔数
    //inpu.insert("clr_type","99959");    //清算方式
    //inpu.insert("refd_setl_flag","0");    //？
    inpud.insert("data",inpu);
    in.insert("input", inpud);

    indoc.setObject(in);
    qDebug()<<"3202 indoc "<<indoc;

    //保存入参日志
    sq = "update com_business set v_in = '"
            + indoc.toJson(QJsonDocument::Compact)
            + "' where jyls = '" + currentMsgid + "'";

    if(!qrm->exec(sq)){
        QMessageBox::information(this,"错误","保存入参日志失败！");
        qDebug()<<sq;
    }

    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
    //request.setHeader(QNetworkRequest::ContentTypeHeader, "multipart/form-data");
    reply = manager.post(request,indoc.toJson());

    //QEventLoop eventLoop;
    QObject::connect(reply, SIGNAL(finished()), &eventLoop, SLOT(quit()));
    eventLoop.exec(); // 进入等待返回，但ui事件循环依然进行。


    qDebug()<<" request 3202 is returned";

    statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);

    if(!statusCode.isValid()){
        QMessageBox::warning(NULL,"注意","http 请求状态错误: " + statusCode.toString());
        return ;
    }

    err = reply->error();

    if(err != QNetworkReply::NoError){
        QMessageBox::warning(NULL,"注意",reply->errorString());
        return ;
    }

    btret = reply->readAll();
    t = QString::fromLocal8Bit(btret);

    //QJsonParseError json_error;

    jsdc = QJsonDocument::fromJson(t.toUtf8(), &json_error);

    if(json_error.error != 0 ){
        QMessageBox::warning(NULL,"注意","返回信息解析错误 " + json_error.errorString());
        return ;
    }
    qDebug()<< "3202 outDoc "<<jsdc;
    jsob = jsdc.object();

    sq = "update com_business set v_out = '"
            + jsdc.toJson(QJsonDocument::Compact)
            + "' where jyls = '" + currentMsgid + "'";

    if(!qrm->exec(sq)){
        QMessageBox::information(this,"错误","保存出参日志失败！");
        qDebug()<<sq;
    }

    if(jsob.value("infcode").toInt() != 0){
        QString t = jsob.value("err_msg").toString();
        QMessageBox::warning(NULL,"注意","3202 交易失败：" + t );
        return ;
    }
    ret3202 = jsob.value("output").toObject().value("fileinfo").toObject();

    qDebug()<<ret3202.value("file_qury_no").toString()
           <<ret3202.value("filename").toString()
          <<ret3202.value("dld_endtime").toString();

    //9102，下载对账结果

    in = d.object();
    inpu = d.object();
    inpud = d.object();

    if(!putBaseIn(  in, "9102") ){
        return;
    }
    //inpu.insert("file_qury_no", ret9101.value("file_qury_no").toString());//	文件查询号
    //inpu.insert("filename", "ret_" + ret9101.value("filename").toString());//
    //inpu.insert("filename", ret9101.value("filename").toString());//
    inpu.insert("file_qury_no", ret3202.value("file_qury_no").toString());//	文件查询号
    inpu.insert("filename", ret3202.value("filename").toString());//

    inpu.insert("fixmedins_code", pub::hos_ybbh);//定点医药机构结

    inpud.insert("fsDownloadIn",inpu);
    in.insert("input", inpud);

    indoc.setObject(in);

    //保存入参日志
    sq = "update com_business set v_in = '"
            + indoc.toJson(QJsonDocument::Compact)
            + "' where jyls = '" + currentMsgid + "'";

    if(!qrm->exec(sq)){
        QMessageBox::information(this,"错误","保存入参日志失败！");
        qDebug()<<sq;
    }

    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
    //request.setHeader(QNetworkRequest::ContentTypeHeader, "multipart/form-data");
    reply = manager.post(request,indoc.toJson());

    //QEventLoop eventLoop;
    QObject::connect(reply, SIGNAL(finished()), &eventLoop, SLOT(quit()));
    eventLoop.exec(); // 进入等待返回，但ui事件循环依然进行。

    qDebug()<<" request 9102 is returned";

    statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);

    if(!statusCode.isValid()){
        QMessageBox::warning(NULL,"注意","http 请求状态错误: " + statusCode.toString());
        return ;
    }

    err = reply->error();

    if(err != QNetworkReply::NoError){
        QMessageBox::warning(NULL,"注意",reply->errorString());
        return ;
    }

    bt = reply->readAll();
    /*
qDebug()<<bt;
    t = QString::fromLocal8Bit(bt);


    jsdc = QJsonDocument::fromJson(t.toUtf8(), &json_error);
    //QJsonDocument jsdc1 = QJsonDocument::fromJson(t.toLocal8Bit(), &json_error);

    if(json_error.error != 0 ){
        QMessageBox::warning(NULL,"注意","返回信息解析错误 " + json_error.errorString());
        //return ;
    }

    qDebug()<< "9102 outDoc "<<jsdc;

    //qDebug()<< "9102 outDoc "<<jsdc;

    jsob = jsdc.object();
    qDebug()<< "9102 outDoc "<<jsob;

//qDebug()<<"9102 bt "<<bt;


*/

    //QFile f1("d:/0down/" + QDateTime::currentDateTime().toString("yyyyMMddHHmmss") +  "-ret.zip");
    QFile f1("d:/0down/" + pureFileName +  "-ret.zip");
    if(!f1.open(QIODevice::WriteOnly)){
        QMessageBox::information(this,"note","create download file failed.");
        return;
    }
    f1.write(bt);
    f1.close();




    QMessageBox::information(this,"注意","对账文件下载完成"  );


}

void Form_jsdz::on_pbExit_clicked()
{
    this->close();
}

bool Form_jsdz::putBaseIn( QJsonObject &in, QString code)
{
    QString inp;
    inp = pub::getYbStrJ(code,"");   //
    if(inp.isEmpty()){
        //pub::useInsurance = false;  //设置医保不可用
        QMessageBox::information(this,"note","申请交易流水号失败！");
        return false; //未能成功申请交易流水号
    }

    currentMsgid = inp;

    in.insert("infno", code);
    in.insert( "msgid", inp);
    in.insert("mdtrtarea_admvs", pub::hos_insuplc);
    //in.insert("insuplc_admdvs", mpPerson["insuplc_admdvs"] );

    in.insert("insuplc_admdvs","210100");
    in.insert("recer_sys_code", "OwnSoft");
    in.insert("dev_no","");
    in.insert("dev_safe_info","");
    in.insert("cainfo", pub::hos_secretcode);
    in.insert("signtype","");
    in.insert("infver", "V1.0");
    in.insert("opter_type", "1");
    in.insert("opter", pub::usr_code);
    in.insert("opter_name", pub::usr_name);
    in.insert("inf_time", QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss"));
    in.insert("fixmedins_code", pub::hos_ybbh);
    in.insert("fixmedins_name", pub::hos_name);
    in.insert("sign_no", pub::sign_no);

    return true;
}

void Form_jsdz::on_pbCalculate_clicked()
{
    sq = "select sum(tot_cost), sum(fund_pay_sumamt), sum(pay_cost), sum(own_cost), count(*) "
         " from fin_ipr_siinmaininfo"
         " where psn_no is not null and insutype = '"
            + ui->cbbXz->currentText() + "' and oper_date > to_date('"
            + ui->deStart->date().toString("yyyy-MM-dd")
            +"','yyyy/mm/dd') and oper_date< to_date('"
            + ui->deEnd->date().toString("yyyy-MM-dd")
            +" 23:59:59','yyyy/mm/dd hh24:mi:ss')" ;
    qDebug()<<sq;
    qro->exec(sq);
    qro->next();
    if( qro->value(4).toInt() == 0 ){
        QMessageBox::information(this,"注意","找不到指定日期的数据！");
        return;
    }
    ui->le1->setText(QString::asprintf("%.2f",qro->value(0).toDouble()));
    ui->le2->setText(QString::asprintf("%.2f",qro->value(1).toDouble()));
    ui->le3->setText(QString::asprintf("%.2f",qro->value(2).toDouble()));
    ui->le4->setText(QString::asprintf("%.2f",qro->value(3).toDouble()));
    ui->le5->setText(qro->value(4).toString());

    if(!ui->cbCreate->isChecked()){
        //未选择生成文件，直接退出
        return;
    }

    QString path = "d:/0down/3202_" + QDateTime::currentDateTime().toString("yyyyMMddhhmmss") + ".txt";

    //创建文件对象
    QFile file;
    //关联文件名字
    file.setFileName(path);
    //打开文件,只写方式
qDebug()<<"filepath "<<path;
    bool isOK = file.open(QIODevice::WriteOnly);
    if (!isOK){
        QMessageBox::information(this,"注意","创建明细文件失败！");
        return;
    }

    sq = "select setl_id, mdtrt_id, psn_no, tot_cost, pub_cost, pay_cost, '0' "
         " from fin_ipr_siinmaininfo"
         //"  where psn_no is not null and oper_date > to_date('"
            " where psn_no is not null and insutype = '"
               + ui->cbbXz->currentText() + "' and oper_date > to_date('"
            + ui->deStart->date().toString("yyyy-MM-dd")
            +"','yyyy/mm/dd') and oper_date< to_date('"
            + ui->deEnd->date().toString("yyyy-MM-dd")
            +" 23:59:59','yyyy/mm/dd hh24:mi:ss')" ;
    qDebug()<<sq;
    qro->exec(sq);
    ui->lwResult->clear();
    QString str ;
    while(qro->next()){
        str = qro->value(0).toString();
        str.append("\t");
        str.append(qro->value(1).toString());
        str.append("\t");
        str.append(qro->value(2).toString());
        str.append("\t");
        str.append(QString::asprintf("%.2f",qro->value(3).toDouble()));
        str.append("\t");
        str.append(QString::asprintf("%.2f",qro->value(4).toDouble()));
        str.append("\t");
        str.append(QString::asprintf("%.2f",qro->value(5).toDouble()));
        str.append("\t");
        str.append(qro->value(6).toString() + "\r\n");

        file.write(str.toLatin1());
        ui->lwResult->addItem(str);
    }
    file.close();

    //write files
    //QString -> QByteArray
    // file.write(str.toUtf8());
    //QString -> C++ string ->char*
    //file.write(str.toStdString().data());
    QMessageBox::information(this,"注意", path+" 文件已生成！");

}
